Imports myBookmarks.Infrastructure
Imports myBookmarks.Core
Namespace myBookmarks.Web
    Public Class BaseController
        Inherits System.Web.Mvc.Controller
        Private _userService As IUserService
        Private Shared ReadOnly CurrentUserKey As Type = GetType(User)

        Private _Settings As IConfigurationSettings
        Public Property Settings() As IConfigurationSettings
            Get
                Return _Settings
            End Get
            Set(ByVal value As IConfigurationSettings)
                _Settings = value
            End Set
        End Property
        Public Sub New(ByVal userservice As IUserService, ByVal settings As IConfigurationSettings)
            _userService = userservice
            _Settings = settings
        End Sub
        Public ReadOnly Property CurrentUserName() As String
            Get
                If HttpContext.User Is Nothing Then
                    Return Nothing
                End If
                Return HttpContext.User.Identity.Name
            End Get
        End Property
        Public ReadOnly Property IsCurrentUserAuthenticated() As Boolean
            Get
                If HttpContext.User.Identity.IsAuthenticated AndAlso (Not CurrentUser Is Nothing) Then
                    Return True
                End If

                Return False
            End Get
        End Property
        Public ReadOnly Property CurrentUser() As User
            Get
                If Not String.IsNullOrEmpty(CurrentUserName) Then
                    Dim user As User = TryCast(HttpContext.Items(CurrentUserKey), User)

                    If user Is Nothing Then
                        user = _userService.GetUserByUsername(CurrentUserName)

                        If user IsNot Nothing Then
                            Try
                                user.LastVisited = DateTime.Now()
                                _userService.SaveUser(user)
                            Catch ex As Exception

                            End Try
                            HttpContext.Items(CurrentUserKey) = user
                        End If
                    End If
                    Return user
                End If
                Return Nothing
            End Get
        End Property
        Public Function CreateViewModel(Of T As {BaseViewModel, New})() As T
            Dim viewData As New T With {.CurrentUser = CurrentUser, _
                                        .MetaDescription = Settings.MetaDescription, _
                                        .MetaKeywords = Settings.MetaKeywords, _
                                        .RootUrl = Settings.RootUrl, _
                                        .SiteTitle = Settings.SiteTitle, _
                                        .FlashMessage = TempData(TempDataKeys.Message)}
            Return viewData
        End Function
    End Class
End Namespace